package com.ym.utils.snapPay;

import com.ym.utils.exception.CustomException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class HttpPostUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpPostUtils.class);
    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static String doPost(String url, String params)throws CustomException {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(12000)
                .setSocketTimeout(12000).setConnectTimeout(12000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        HttpEntity entity = new StringEntity(params, ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(entity);
        CloseableHttpResponse resp = null;
        InputStream inputStream =null;
        try {
            resp = httpClient.execute(httpPost);
            int httpRc = resp.getStatusLine().getStatusCode();
            if (httpRc == 200) {
                inputStream = resp.getEntity().getContent();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                String mapJson = result.toString(StandardCharsets.UTF_8.name());
                return mapJson;
            }
        } catch (ConnectTimeoutException ex){
            logger.error("调用异常"+ ex.toString());
            throw new CustomException(500,"链接超时");
        } catch (Exception ex) {
            logger.error("调用异常"+ ex.toString());
            throw new CustomException(500,"调用异常");
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
                if (null != resp) {
                    resp.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}